#include "whitenoiseplayer.h"
#include <QVBoxLayout>
#include <QFile>
#include <QFileInfo>

// 构造函数
WhiteNoisePlayer::WhiteNoisePlayer(QWidget *parent)
    : QWidget(parent), audioOutput(nullptr), audioBuffer(nullptr), isPlaying(false) {

    QVBoxLayout *layout = new QVBoxLayout(this);

    // 创建标签和下拉框
    QLabel *instructionLabel = new QLabel("请选择白噪音类型：", this);
    noiseSelector = new QComboBox(this);
    noiseSelector->addItem("舒缓海浪", "src/plugins/myClock/noise/sea.wav");
    noiseSelector->addItem("伞下雨声", "src/plugins/myClock/noise/rain.wav");
    noiseSelector->addItem("温馨火苗", "src/plugins/myClock/noise/flame.wav");
    noiseSelector->addItem("夜晚虫鸣", "src/plugins/myClock/noise/chirping.wav");
    // 创建播放/暂停按钮
    playPauseButton = new QPushButton("播放", this);

    // 布局控件
    layout->addWidget(instructionLabel);
    layout->addWidget(noiseSelector);
    layout->addWidget(playPauseButton);

    // 连接信号和槽
    connect(playPauseButton, &QPushButton::clicked, this, &WhiteNoisePlayer::togglePlayback);
    connect(noiseSelector, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &WhiteNoisePlayer::loadNoise);

    // 加载默认白噪音
    loadNoise(0);
}

// 析构函数
WhiteNoisePlayer::~WhiteNoisePlayer() {
    stopPlaying();
}

// 加载白噪音文件
void WhiteNoisePlayer::loadNoise(int index) {
    // 如果正在播放，停止当前播放
    if (isPlaying) {
        stopPlaying();
    }

    // 打开选定的音频文件
    QString noiseFile = noiseSelector->currentData().toString();
    QFile file(noiseFile);
    if (!file.open(QIODevice::ReadOnly)) {
        qWarning("无法打开音频文件: %s", qPrintable(noiseFile));
        return;
    }

    // 将音频数据加载到内存
    audioData = file.readAll();
    file.close();

    // 重新开始播放
    startPlaying();
}

// 开始播放音频
void WhiteNoisePlayer::startPlaying() {
    // 创建音频缓冲区并加载音频数据
    if (!audioBuffer) {
        audioBuffer = new QBuffer(this);
    }
    audioBuffer->setData(audioData);
    audioBuffer->open(QIODevice::ReadOnly);

    // 创建音频输出设备
    if (!audioOutput) {
        QAudioFormat format;
        format.setSampleRate(44100);
        format.setChannelCount(2);
        format.setSampleSize(16);
        format.setCodec("audio/pcm");
        format.setByteOrder(QAudioFormat::LittleEndian);
        format.setSampleType(QAudioFormat::SignedInt);

        audioOutput = new QAudioOutput(format, this);
        connect(audioOutput, &QAudioOutput::stateChanged, this, &WhiteNoisePlayer::handleAudioStateChange);
    }

    // 开始播放
    audioOutput->start(audioBuffer);
    isPlaying = true;
    playPauseButton->setText("暂停");
}

// 停止播放音频
void WhiteNoisePlayer::stopPlaying() {
    if (audioOutput) {
        audioOutput->stop();
        delete audioOutput;
        audioOutput = nullptr;
    }
    if (audioBuffer) {
        audioBuffer->close();
        delete audioBuffer;
        audioBuffer = nullptr;
    }
    isPlaying = false;
    playPauseButton->setText("播放");
}

// 播放/暂停切换
void WhiteNoisePlayer::togglePlayback() {
    if (isPlaying) {
        stopPlaying();
    } else {
        startPlaying();
    }
}

// 处理音频状态变化
void WhiteNoisePlayer::handleAudioStateChange(QAudio::State state) {
    if (state == QAudio::IdleState) {
        // 文件播放完成，重新开始
        audioBuffer->seek(0);  // 将音频流指针重置为开始位置
        audioOutput->start(audioBuffer);  // 重新开始播放
    } else if (state == QAudio::StoppedState && audioOutput->error() != QAudio::NoError) {
        qWarning("音频播放错误");
    }
}
